#include "Client.h"

Client::Client(void) :
	stopped_(false),
	update_timer_(io_service_,boost::posix_time::milliseconds(100)),
	last_update_time(0)
	
{
// 	signals_.add(SIGINT);
// 	signals_.add(SIGTERM);
// #if defined(SIGQUIT)
// 	signals_.add(SIGQUIT);
// #endif // defined(SIGQUIT)
// 	signals_.async_wait(boost::bind(&Client::handleStop, this));
}

Client::~Client(void)
{
}

void Client::onConnClosed(ConnectionPtr c)
{
	connection_manager_.stop(c);
}

void Client::handleStop()
{
	LogFunctionEnter;

	// The Server is stopped by cancelling all outstanding asynchronous
	// operations. Once all operations have finished the io_service::run() call
	// will exit.

	connection_manager_.stop_all();

	update_timer_.cancel();
	stopped_ = true;
}

void Client::stop()
{
	stopped_ = true;
}

void Client::handleConnect(ConnectionPtr c, const boost::system::error_code& error)
{
	if (stopped_)
		return;

	if (!error)
	{
		c->start();
	}
}

void Client::onUpdate(const boost::system::error_code& error)
{
	if (stopped_)
		return;

	if (!error)
	{
		//LOG_INFO << "onUpdate";
		doUpdate();
		update_timer_.expires_from_now(boost::posix_time::milliseconds(100));
		update_timer_.async_wait(boost::bind(&Client::onUpdate,this,boost::asio::placeholders::error));
	}
}

void Client::run()
{
	LogFunctionEnter;

	last_update_time = getMsTime();
	doUpdate();
	update_timer_.expires_from_now(boost::posix_time::milliseconds(100));
	update_timer_.async_wait(boost::bind(&Client::onUpdate,this,boost::asio::placeholders::error));

	io_service_.run();

	LogFunctionLeave;
}

void Client::doUpdate()
{
	if (stopped_)
	{
		handleStop();
		return;
	}

	uint32 current_time = getMsTime();
	uint32 time_diff = 0;
	if (current_time < last_update_time)
	{
		time_diff = uint32(-1) - last_update_time + current_time;
	}
	else
		time_diff = current_time - last_update_time;

	last_update_time = current_time;

	
	connection_manager_.update(time_diff);

// 	if (connected_)
// 	{
// 		update_data_timer_.update(time_diff);
// 
// 		if (update_data_timer_.passed())
// 		{
// 			update_data_timer_.reset();
// 
// 			{
// 				boost::lock_guard<boost::mutex> lg(mutex_);
// 				boost::swap(m_incoming,m_outcoming);
// 			}
// 
// 			for (StringSequence::const_iterator it = m_outcoming->begin();
// 				it != m_outcoming->end(); ++it)
// 			{
// 				connection_->pushData(*it);
// 			}
// 
// 			m_outcoming->clear();
// 		}
// 	}

}

